package com.example.tsproject.Controller;

import com.example.tsproject.entity.Assignments;
import com.example.tsproject.entity.Result;
import com.example.tsproject.service.AssignmentsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import java.util.List;


@RestController
@RequestMapping("/assignments")
public class AssignmentsController {

    @Autowired
    private AssignmentsService assignmentsService;

    // Existing methods...

    // Submit answers for an assignment
    @PostMapping("/submitAnswers")
    public Result submitAnswers(@RequestBody Map<String, Object> payload) {
        String assignmentIdStr = (String) payload.get("assignmentId");
        Integer assignmentId = Integer.parseInt(assignmentIdStr);
        List<Map<String, Object>> userAnswers = (List<Map<String, Object>>) payload.get("userAnswers");

        boolean isSubmitted = assignmentsService.submitAnswers(assignmentId, userAnswers);
        if (isSubmitted) {
            return Result.success("Answers submitted successfully");
        } else {
            return Result.error("Failed to submit answers");
        }
    }
    @GetMapping("/delete")
    public Result delete(@RequestParam("ass_id") Integer ass_id){
       assignmentsService.delete(ass_id);
       return Result.success();
    }
    @GetMapping("/Tdelete")
    public Result Tdelete(@RequestParam("class_number") String class_number,@RequestParam("name") String name){
        assignmentsService.Tdelete(class_number,name);
        System.out.println("--------------------");
        return Result.success();
    }
    @GetMapping("/examTime/{assignmentId}")
    public Result getExamTime(@PathVariable("assignmentId") Integer assignmentId) {
        // 根据 assignmentId 查询考试时间
        Map<String, String> examTime = new HashMap<>();
        Assignments assignments = assignmentsService.getById(assignmentId);

        System.out.println("*************************");
        System.out.println(assignments);

        Date start_time = assignments.getStart_time();
        Date end_time = assignments.getEnd_time();

        System.out.println(start_time);
        System.out.println(end_time);

        // 转换为 ISO 8601 格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'")
                .withZone(ZoneId.systemDefault());

        String start_time_iso = formatter.format(start_time.toInstant());
        String end_time_iso = formatter.format(end_time.toInstant());

        examTime.put("start_time", start_time_iso);
        examTime.put("end_time", end_time_iso);

        System.out.println(start_time_iso);
        System.out.println(end_time_iso);

        return Result.success(examTime);
    }
}
